<?php
function jsonToPage($json){
    return $str;
}


function getfiles( $path , &$files = array() )
{
    if ( !is_dir( $path ) ) return null;
    $handle = opendir( $path );
    while ( false !== ( $file = readdir( $handle ) ) ) {
        if ( $file != '.' && $file != '..' ) {
            $path .= substr($path, -1) == '/' ? '' : '/';
            $path2 = $path . $file;
            if ( is_dir( $path2 ) ) {
                $v['type'] = 'dir';
                $v['fname'] = $file;
                $v['fpath'] = $path2;
                $files[] = $v;
                getfiles( $path2 , $files );
            } else {
                $v['type'] = 'file';
                $v['fname'] = $file;
                $v['fpath'] = $path2;
                $files[] = $v;
            }
        }
    }
    return $files;
}


function delDir($path)
{
    if(is_dir($path))
    {
            $file_list= scandir($path);
            foreach ($file_list as $file)
            {
                if( $file!='.' && $file!='..')
                {
                    my_del($path.'/'.$file);
                }
            }
            @rmdir($path);    
    }
    else
    {
        @unlink($path);
    }
 
}


function zipApiCould($fiels,$savezip,$zipdir = 'widget/') {
    set_time_limit(0);
    $zip = new \ZipArchive();
    // $zip->open($savezip,ZIPARCHIVE::OVERWRITE);
    $zip->open($savezip,ZIPARCHIVE::CREATE);
    foreach ($fiels as $k) {
        if ($k['type'] == 'dir') continue;
        $localname = $zipdir.$k['fpath'];
        if ($k['fname'] == 'config.apicould.xml') {
            $localname = $zipdir.$k['fname'];
        }elseif ($k['fname'] == 'config.xml') {
            $localname = $zipdir.$k['fname'];
        }elseif ($k['fname'] == 'index.html') {
            $localname = $zipdir.$k['fname'];
        }
        $localname = str_replace("User/ApiCloud/default", "", $localname);
        $zip->addFile($k['fpath'],$localname);
    }
    $zip->close();
}

/**
 * 解压文件
 */
function ezip($zip, $hedef = ''){
    $dirname=preg_replace('/.zip/', '', $zip);
    $root = $_SERVER['DOCUMENT_ROOT'].'/zip/';
    $zip = zip_open($root . $zip);
    @mkdir($root . $hedef . $dirname.'/'.$zip_dosya);
    while($zip_icerik = zip_read($zip)){
        $zip_dosya = zip_entry_name($zip_icerik);
        if(strpos($zip_dosya, '.')){
            $hedef_yol = $root . $hedef . $dirname.'/'.$zip_dosya;
            @touch($hedef_yol);
            $yeni_dosya = @fopen($hedef_yol, 'w+');
            @fwrite($yeni_dosya, zip_entry_read($zip_icerik));
            @fclose($yeni_dosya); 
        }else{
            @mkdir($root . $hedef . $dirname.'/'.$zip_dosya);
        };
    };
}

//将数字转换为目录 例如  31  =   000/000/31
function numberDir($num = 0) {
    if ($num == 0) $num = date('Ymd');
    $num = sprintf("%07d", $num);
    $dir1 = substr($num, 0, 3);
    $dir2 = substr($num, 3, 2);
    $dir3 = substr($num, 5, 2);
    return $dir1.'/'.$dir2.'/'.$dir3.'/';
}

//下载文件
function download_file($file,$downame){
    if(is_file($file)){
        $length = filesize($file);
        $type = mime_content_type($file);
        if ($downame) {
            $showname = $downame;
        }else{
            $showname =  ltrim(strrchr($file,'/'),'/');
        }
        header("Content-Description: File Transfer");
        header('Content-type: ' . $type);
        header('Content-Length:' . $length);
         if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) { //for IE
             header('Content-Disposition: attachment; filename="' . rawurlencode($showname) . '"');
         } else {
             header('Content-Disposition: attachment; filename="' . $showname . '"');
         }
         readfile($file);
         exit;
     } else {
         exit('文件不存在！');
     }
 }

//将cookie 转换为数组
function cookieToArr($ck = ''){
    $c_arr = explode(';',$ck);
    $cookie = array();
    foreach($c_arr as $item) {
        $kitem = explode('=',trim($item));
        if (count($kitem)>1) {
            $key = trim($kitem[0]);
            $val = trim($kitem[1]);
            if (!empty($val)) $cookie[$key] = $val;
        }
    }
    return $cookie;
}


//根据字符串返回被包含的字符
function getWordsByStr($inStr,$findStr)
{
    $rt = array();
    foreach ($findStr as $k) {
        if (strstr($inStr,$k)) {
            array_push($rt, $k);
        }
    }
    return $rt;
}


function cut( $Str, $Length,$sss = '' ) {
    //$Str为截取字符串，$Length为需要截取的长度
    global $s;
    $i = 0;
    $l = 0;
    $ll = strlen( $Str );
    $s = $Str;
    $f = true;
    //if(isset($Str{$i}))
    while ( $i <= $ll ) {
    if ( ord( $Str{$i} ) < 0x80 ) {
    $l++; $i++;
    } else if ( ord( $Str{$i} ) < 0xe0 ) {
    $l++; $i += 2;
    } else if ( ord( $Str{$i} ) < 0xf0 ) {
    $l += 2; $i += 3;
    } else if ( ord( $Str{$i} ) < 0xf8 ) {
    $l += 1; $i += 4;
    } else if ( ord( $Str{$i} ) < 0xfc ) {
    $l += 1; $i += 5;
    } else if ( ord( $Str{$i} ) < 0xfe ) {
    $l += 1; $i += 6;
    }

    if ( ( $l >= $Length - 1 ) && $f ) {
    $s = substr( $Str, 0, $i );
    $f = false;
    }

    if ( ( $l > $Length ) && ( $i < $ll ) ) {
    $s = $s . '...'; break; //如果进行了截取，字符串末尾加省略符号“...”
    // $s = $s . $sss; break; //如果进行了截取，字符串末尾加省略符号“...”
    }
    }
    return $s;
}

function getBrowser(){
    $agent=$_SERVER["HTTP_USER_AGENT"];
    if(strpos($agent,'MSIE')!==false || strpos($agent,'rv:11.0')) //ie11判断
    return "ie";
    else if(strpos($agent,'Firefox')!==false)
    return "firefox";
    else if(strpos($agent,'Chrome')!==false)
    return "chrome";
    else if(strpos($agent,'Opera')!==false)
    return 'opera';
    else if((strpos($agent,'Chrome')==false)&&strpos($agent,'Safari')!==false)
    return 'safari';
    else
    return 'unknown';
}

/** 获取当前时间戳，精确到毫秒 */
function microtime_float()
{
   list($usec, $sec) = explode(" ", microtime());
   return ((float)$usec + (float)$sec);
}

function getRandChar($length,$t){
    $str = null;
    $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
    if ($t == 1) {
        $strPol = "0123456789";
    }elseif ($t == 2) {
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    }
    $max = strlen($strPol)-1;

    for($i=0;$i<$length;$i++){
        $str.=$strPol[rand(0,$max)];
    }

    return $str;
}

function dejson($str){
    $str = str_replace("\\", '', $str);
    $str = str_replace("\n", '', $str);
    $str = str_replace("\r\n", '', $str);
    return $str;
}
//创建临时模板用的
function createTmpTpl()
{
    $f = fopen("a.txt", "r");
    while (!feof($f)) {
        $line = fgets($f);
        $ll = explode('",\'', $line);
        if (!$ll[0] || !$ll[1]) continue;
        $fp = "/Volumes/Hard/Users/anyhome/www/easyapps_cc/editor/".$ll[0];
        $dir = dirname($fp);
        if (!file_exists($dir)) {
            mkdir($dir,0777,true);
        }
        $cc = $ll[1];
        $cc = str_replace("style=\"{", "style=\"", $cc);
        $cc = str_replace("\\n", "", $cc);
        $cc = str_replace("    ", "", $cc);
        $cc = unicodeString($cc);        
        $cc = stripslashes($cc);        
        file_put_contents($fp, $cc);
    }
}
function unicodeString($str, $encoding=null) { 
    return preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/u', create_function('$match', 'return mb_convert_encoding(pack("H*", $match[1]), "utf-8", "UTF-16BE");'), $str);
}

function toDatetime( $time, $format = 'Y-m-d H:i:s' ) {
  if ( empty ( $time ) ) {
    return "";
  }
  if ( is_numeric( $time ) ) {
    return date( $format, $time );
  }
  $format = str_replace( '#', ':', $format );
  return date( $format, strtotime( $time ) );
}

function toDate( $time, $format = 'Y-m-d' ) {
  if ( empty ( $time ) ) {
    return $time;
  }
  $format = str_replace( '#', ':', $format );
  return date( $format, $time );
}